<?php
/**
 * crcl/base
 *
 * Copyright 2013 CRCL - André Sabosch - info@crcl.de
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

namespace crcl\base\xml\sax;

interface IBuilder
{
  public function getBuild();
}

class Builder extends \crcl\base\xml\Sax implements IBuilder
{
  public function getBuild()
  {
    return $this->sBuild;
  }

  public function extendBuild($sContent)
  {
    $this->sBuild .= $sContent;
  }

  public function onDocumentStart()
  {
    $this->sBuild = '';
  }

  public function onDocumentEnd()
  {
    $this->sBuild = \trim($this->sBuild);
  }

  public function onDocumentType($sDoctype)
  {
    $this->sBuild .= $sDoctype;
  }

  public function onElementData($sData)
  {
    $this->sBuild .= $sData;
  }

  public function onElementStart($sTagName, $aAttributes, $bShort = \FALSE)
  {
    $this->bLastShort = $bShort;

    $this->sBuild .= '<' . $sTagName;
    foreach ($aAttributes as $sAttribute => $sValue)
    {
      $this->sBuild .= ' ' . $sAttribute . '="' . $sValue . '"';
    }
    if ($bShort !== \TRUE)
    {
      $this->sBuild .= '>';
    }
  }

  public function onElementClose($sTagName)
  {
    if ($this->bLastShort)
    {
      $this->sBuild .= ' />';
      $this->bLastShort = \FALSE;
    }
    else
    {
      $this->sBuild .= '</' . $sTagName . '>';
    }
  }

  public function onComment($sComment)
  {
    $this->sBuild .= '<!--' . $sComment . '-->';
  }

  public function onCDATASection($sCDATA)
  {
    $this->sBuild .= '<![CDATA[' . $sCDATA . ']]>';
  }

  public function onXmlDeclaration($sDeclaration)
  {
    $this->sBuild .= $sDeclaration;
  }

  public function onProcessingInstruction($sInstruction)
  {
    $this->sBuild .= $sInstruction;
  }

  /** PROTECTED ***********************************************************************************/

  protected $sBuild = '';
  protected $bLastShort = \FALSE;
}